Skip to content

prevent callback skipping with triggerOnce and merged refs#747

Open
djk01281 wants to merge 1 commit intothebuilder:mainfrom
djk01281:fix/triggeronce-merged-refs
Open

prevent callback skipping with triggerOnce and merged refs#747
djk01281 wants to merge 1 commit intothebuilder:mainfrom
djk01281:fix/triggeronce-merged-refs

Conversation

@djk01281
Copy link

@djk01281 djk01281 commented Feb 3, 2026

Hello! 👋🏻 I ran into this bug while using multiple useInView hooks with merged refs, so I opened an issue and put together this fix.

Let me know if anything needs to be changed!

Loving the library by the way : )

Description

Fixes #746

This PR fixes a bug where callbacks are skipped when multiple useInView({ triggerOnce: true }) hooks are merged on the same element.

Problem

When a callback executes with triggerOnce: true, it calls unobserve() which removes the callback from the array using splice(). This modifies the array during forEach iteration, causing subsequent callbacks to be skipped.

Solution

Copy the callbacks array before iterating using the spread operator:

[...elements.get(entry.target) ?? []].forEach((callback) => {
  callback(inView, entry);
});

This prevents the iteration from being affected by array modifications.

Changes

  • src/observe.ts: Use spread operator to copy callbacks array before iteration
  • src/tests/useInView.test.tsx: Add test case to verify all callbacks are triggered with triggerOnce and merged refs

Testing

Added a new test that reproduces the bug:

  • Creates 3 useInView hooks with triggerOnce: true
  • Merges all refs onto a single element
  • Verifies all 3 hooks receive inView: true
image

Before fix: Test fails - only hooks 1 and 3 trigger, hook 2 remains false


image

After fix: Test passes - all 3 hooks trigger correctly : )

@bolt-new-by-stackblitz
Copy link

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@vercel
Copy link

vercel bot commented Feb 3, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
react-intersection-observer Ready Ready Preview, Comment Feb 3, 2026 1:36pm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🐛 Bug: Callbacks skipped when using triggerOnce with merged refs

1 participant